﻿using System;
using System.IO;
using System.Xml;

namespace todo.Persistence
{
    public class TitleParser
    {
        public static string Parse(string fileName)
        {
            var inTitle = false;
            Console.WriteLine(fileName);
            try
            {
                if (new FileInfo(fileName).Length < 1)
                {
                    return null;
                }
            }
            catch (FileNotFoundException e)
            {
                return null;
            }
            using (var reader = XmlReader.Create(fileName))
            {
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            if (reader.Name == "title")
                            {
                                inTitle = true;
                            }
                            break;
                        case XmlNodeType.Text:
                            if (inTitle)
                            {
                                return reader.Value;
                            }
                            break;
                        case XmlNodeType.EndElement:
                            if (inTitle)
                            {
                                return null;
                            }
                            break;
                    }
                }
            }
            return null;
        }
    }
}